﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sistema_Test_OnLine.Model;
using Sistema_Test_OnLine.Logic;
using System.Security.Cryptography;
using System.Text;

using ASPNETChat;
using System.Web.Services;

namespace Sistema_Test_OnLine
{
    public partial class Layout : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (Session["UserName"] == null)
            //    Response.Redirect("Recuperar_pass.aspx");
            //if (string.IsNullOrEmpty(Request.QueryString["rid"]))
            //    Response.Redirect("Recuperar_pass.aspx");

            txtMsg.Attributes.Add("onkeypress", "return clickButton(event,'btn')");
            if (!IsPostBack && Session["user"] != null)
            {
                //hdnRoomID.Value = Request.QueryString["rid"];
                ChatRoom room = ChatEngine.GetRoom("1");
                string prevMsgs = room.JoinRoom(((Sistema_Test_OnLine.Model.User)Session["user"]).Nombre.ToString(), ((Sistema_Test_OnLine.Model.User)Session["user"]).Nombre.ToString());
                txt.Text = prevMsgs;
                foreach (string s in room.GetRoomUsersNames())
                {
                    lstMembers.Items.Add(new ListItem(s, s));
                }
            }
        }
        protected void btnIniciarSesion_Click(object sender, EventArgs e)
        {
            String login = TextBox1.Text;

            String password = GetMD5(TextBox2.Text);

            List<User> userL = Facade.GetUsers("login='" + login + "' and password='" + password + "'");
            if (userL.Count == 0)
            {
                Label1.Text = "Olvidaste tu contraseña??";
            }
            else
            {
                Session["user"] = userL[0];
                Response.Redirect("Inicio.aspx");
            }
        }

        public static string GetMD5(string str)
        {
            MD5 md5 = MD5CryptoServiceProvider.Create();
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] stream = null;
            StringBuilder sb = new StringBuilder();
            stream = md5.ComputeHash(encoding.GetBytes(str));
            for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
            return sb.ToString();
        }

        protected void Cerrar_Sesion_Click(object sender, EventArgs e)
        {
            Session["user"] = null;
        }

        #region Script Callback functions

        [WebMethod]
        static public string SendMessage(string msg, string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom("1");
                string res = "";
                if (room != null)
                {
                    res = room.SendMessage("hola", HttpContext.Current.Session["user"].ToString());
                }
                return res;
            }
            catch (Exception ex)
            {

            }
            return "";
        }

        [WebMethod]
        static public string UpdateUser(string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                if (room != null)
                {
                    string res = "";
                    if (room != null)
                    {
                        res = room.UpdateUser(HttpContext.Current.Session["user"].ToString());
                    }
                    return res;
                }
            }
            catch (Exception ex)
            {

            }
            return "";
        }

        [WebMethod]
        static public string LeaveRoom(string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                if (room != null)
                    room.LeaveRoom(HttpContext.Current.Session["user"].ToString());
            }
            catch (Exception ex)
            {

            }
            return "";
        }

        [WebMethod]
        static public string UpdateRoomMembers(string roomID)
        {
            try
            {
                ChatRoom room = ChatEngine.GetRoom(roomID);
                if (room != null)
                {
                    IEnumerable<string> users = room.GetRoomUsersNames();
                    string res = "";

                    foreach (string s in users)
                    {
                        res += s + ",";
                    }
                    return res;
                }
            }
            catch (Exception ex)
            {
            }
            return "";
        }

        #endregion

        protected void Editar_Usuario_Click(object sender, EventArgs e)
        { 
        
        }
        protected void Darme_de_Baja_Click(object sender, EventArgs e)
        { 
        
        }
    }
}